<template>
  <div class="course-outline">
    <h3>课程目录编辑</h3>
    <!-- 可编辑文本框 -->
    <textarea
      v-model="content"
      placeholder="请输入课程目录内容..."
      class="editable-textarea"
      rows="20"
    ></textarea>
    <!-- 显示加载提示，置于 textarea 内部 -->
    <div v-if="loadingContent" class="loading-indicator-inside">
      <el-spinner size="small"></el-spinner> 正在提取...
    </div>

    <!-- 上传和智能识别按钮 -->
    <div class="action-buttons">
      <input type="file" ref="fileInput" @change="handleFileUpload" style="display: none;" />
      <button @click="triggerFileUpload">上传PDF文件</button>
      <button :disabled="!fileId" @click="runIntelligentRecognition">提取课程目录</button>
    </div>

    <!-- 保存按钮 -->
    <div class="save-button">
      <button @click="saveContent">保存</button>
    </div>
  </div>
</template>

<script>
import axios from "axios"; // 用于处理 API 请求

export default {
  name: "CourseOutline",
  data() {
    return {
      content: "", // 文本框的内容
      fileId: null, // 上传后的文件 ID
      user: "abc-123", // 用户标识
      token: "Bearer app-AtLAcsf37wgSsEuw37mDslfk", // 替换为实际的 Bearer Token
      loadingContent: false, // 用于控制加载状态
    };
  },
  methods: {
    // 触发文件选择对话框
    triggerFileUpload() {
      this.$refs.fileInput.click();
    },

    // 上传文件
    async handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      const formData = new FormData();
      formData.append("file", file); // 添加文件
      formData.append("user", "abc-123"); // 添加用户标识

      try {
        const response = await axios.post("http://10.109.119.86:8080/v1/files/upload", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: this.token, // 添加 Bearer Token
          },
        });

        if (response.status === 201) {
          // 上传成功
          this.fileId = response.data.id;
          alert("上传成功！");
        } else {
          alert(`上传失败：HTTP ${response.status}`);
        }
      } catch (error) {
        console.error("上传失败", error);
        alert("上传失败，请重试！");
      }
    },

    // 智能识别
    async runIntelligentRecognition() {
      this.loadingContent = true;
      if (!this.fileId) {
        alert("请先上传文件！");
        this.loadingContent = false; // 确保在未上传文件时关闭加载状态
        return;
      }

      try {
        const response = await axios.post(
          "http://10.109.119.86:8080/v1/workflows/run",
          {
            inputs: {
              input: [
                {
                  transfer_method: "local_file",
                  upload_file_id: this.fileId,
                  type: "document",
                },
              ],
            },
            response_mode: "blocking",
            user: "abc-123", // 添加用户标识
          },
          {
            headers: {
              Authorization: this.token, // 添加 Bearer Token
            },
          }
        );

        // 验证返回结果
        if (response.status === 200) {
          const data = response.data.data; // 获取 data 字段
          if (data && data.outputs && data.outputs.answer) {
            // 渲染结果到文本框
            this.content = data.outputs.answer;
            alert("智能识别成功！");
          } else {
            alert("智能识别成功，但未返回有效内容！");
          }
        } else {
          alert(`智能识别失败：HTTP ${response.status}`);
        }
      } catch (error) {
        // 捕获异常并显示错误信息
        console.error("智能识别失败", error);
        alert("智能识别失败，请重试！");
      }finally {
        this.loadingContent = false;
      }

    },

    // 保存内容到 localStorage
    saveContent() {
      if (this.content.trim() === "") {
        alert("内容为空，无法保存！");
        return;
      }

      // 保存到 localStorage
      localStorage.setItem("courseOutlineContent", this.content);
      alert("内容已保存！");
    },
  },
};
</script>

<style scoped>
.course-outline {
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
}

.editable-textarea {
  width: 100%;
  padding: 10px;
  font-size: 16px;
  line-height: 1.5;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: vertical;
}

.action-buttons {
  margin-top: 20px;
}

.action-buttons button {
  margin-right: 10px;
}

.save-button {
  margin-top: 20px;
  text-align: right;
}

.save-button button {
  padding: 10px 15px;
  font-size: 14px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.save-button button:hover {
  background-color: #0056b3;
}

.loading-indicator-inside {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #888;
}
</style>
